package utils

import (
	"github.com/bytedance/sonic"
	"github.com/golang-module/dongle"
	"github.com/jefferyjob/go-easy-utils/anyUtil"
	"github.com/jeremywohl/flatten"
	"sort"
	"strings"
)

func digestJsonText(data, skipPrefix string) ([]byte, error) {
	var m map[string]any
	if err := sonic.UnmarshalString(data, &m); err != nil {
		return nil, err
	}

	var keys []string
	for k, _ := range m {
		if skipPrefix != "" {
			if !strings.HasPrefix(k, skipPrefix) {
				keys = append(keys, k)
			}
		} else {
			keys = append(keys, k)
		}
	}

	sort.Strings(keys)
	var items []string
	for _, k := range keys {
		v := m[k]
		item := k + "=" + anyUtil.AnyToStr(v)
		items = append(items, item)
	}

	msg := strings.Join(items, "&")
	return dongle.Encrypt.FromString(msg).BySha256().ToRawBytes(), nil
}

func DigestJsonStruct(obj any, skipPrefix string) ([]byte, error) {
	data, err := sonic.MarshalString(obj)
	if err != nil {
		return nil, err
	}

	flat, err := flatten.FlattenString(data, "", flatten.DotStyle)
	if err != nil {
		return nil, err
	}

	return digestJsonText(flat, skipPrefix)
}

func DigestJsonText(data, skipPrefix string) ([]byte, error) {
	flat, err := flatten.FlattenString(data, "", flatten.DotStyle)
	if err != nil {
		return nil, err
	}

	return digestJsonText(flat, skipPrefix)
}
